package cn.snowheart.strategy.spring.context;

import cn.snowheart.strategy.spring.annotation.HandlerType;
import cn.snowheart.strategy.spring.enums.OrderType;
import cn.snowheart.strategy.spring.handler.IOrderHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuwanxiang
 * @version 2019/06/24
 */
@Configuration
public class ContextConfiguration {

    /**
     * 利用ApplicationContext初始化HandlerContext
     *
     * @param context ApplicationContext
     * @return HandlerContext
     */
    @Bean
    public HandlerContext handlerContext(ApplicationContext context) {
        Map<OrderType, IOrderHandler> contextMap = new HashMap<>();
        Map<String, IOrderHandler> map = context.getBeansOfType(IOrderHandler.class);
        if (map != null && !map.isEmpty()) {
            Collection<IOrderHandler> handlers = map.values();
            for (IOrderHandler handler : handlers) {
                OrderType handlerType = handler.getClass().getAnnotation(HandlerType.class).value();
                contextMap.put(handlerType, handler);
            }
        }
        return new HandlerContext(contextMap);
    }

}
